package com.woniuxy.house.web;

import com.woniuxy.house.exception.AccountExistException;
import com.woniuxy.house.exception.AccountNotExistException;
import com.woniuxy.house.exception.CaptchaMistakeException;
import com.woniuxy.house.exception.PasswordMistakeException;
import com.woniuxy.house.vo.ResponseEntity;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 异常处理器
 * @author baobo
 * @date 2022-08-29-15:18
 */
@RestControllerAdvice("com.woniuxy.house.web")
public class ExceptionAdvisor {


	//  MethodArgumentNotValidException
	@ExceptionHandler(MethodArgumentNotValidException.class)
	public ResponseEntity handlerMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		e.printStackTrace();
		Map map = new HashMap<>();
		//得到所有错误
		e.getFieldErrors().forEach(r -> {
			map.put(r.getField(), r.getDefaultMessage());
		});
		return new ResponseEntity("500", "error", map);
	}

	//ConstraintViolationException
	@ExceptionHandler(ConstraintViolationException.class)
	public ResponseEntity handlerConstraintViolationException(ConstraintViolationException e) {
		e.printStackTrace();
		Map map = new HashMap<>();
		//得到所有错误
		e.getSuppressed();
		e.getConstraintViolations().forEach(r -> {
			map.put(r.getPropertyPath(),r.getMessage());
		});
		return new ResponseEntity("500", "error", map);
	}
	@ExceptionHandler(AccountExistException.class)
	public ResponseEntity handlerAccountExistException(AccountExistException e) {
		e.printStackTrace();
		Map map = new HashMap<>();
		//得到所有错误
		return new ResponseEntity("500", "账号已存在", e.getSuppressed());
	}
	@ExceptionHandler(CaptchaMistakeException.class)
	public ResponseEntity handlerCaptchaMistakeException(CaptchaMistakeException e) {
		e.printStackTrace();
		Map map = new HashMap<>();
		//得到所有错误
		return new ResponseEntity("500", "验证码错误", e.getSuppressed());
	}
	@ExceptionHandler(AccountNotExistException.class)
	public ResponseEntity handlerAccountNotExistException(AccountNotExistException e) {
		e.printStackTrace();
		Map map = new HashMap<>();
		//得到所有错误
		return new ResponseEntity("501", "账号或密码错误", e.getSuppressed());
	}
	@ExceptionHandler(PasswordMistakeException.class)
	public ResponseEntity handlerPasswordMistakeException(PasswordMistakeException e) {
		e.printStackTrace();
		Map map = new HashMap<>();
		//得到所有错误
		return new ResponseEntity("501", "密码错误", e.getSuppressed());
	}

}
